﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Event.Share;
using Windows.Infrastructure.Share.Security;
using Windows.Infrastructure.Share.Tools;

namespace Windows.Api.Share.Filter
{
    public class LogOperateAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 接口名称，例如 模块修改
        /// </summary>
        public string ApiName { get; set; } = "";
        public LogOperateAttribute(string apiName)
        {
            ApiName = apiName;
        }
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            ICapPublisher capPublisher = (ICapPublisher)context.HttpContext.RequestServices.GetService(typeof(ICapPublisher))!;
            ICurrentUser currentUser = (ICurrentUser)context.HttpContext.RequestServices.GetService(typeof(ICurrentUser))!;

            var sw = new Stopwatch();
            sw.Start();
            var actionResult = (await next()).Result;
            sw.Stop();

            //获取到body值
            context.HttpContext.Request.Body.Position = 0;
            using var requestReader = new StreamReader(context.HttpContext.Request.Body);
            var request = await requestReader.ReadToEndAsync();
            context.HttpContext.Request.Body.Position = 0;

            string response = "";
            bool isSuccess = false;
            if (actionResult != null)
            {
                isSuccess = true;
                if (actionResult is EmptyResult)
                {
                    response = "";
                }
                else
                {
                    response = JsonConvert.SerializeObject((actionResult as ObjectResult)!.Value);
                }
            }
            string ua = context.HttpContext.Request.Headers["User-Agent"];
            var client = UAParser.Parser.GetDefault().Parse(ua);
            LogOperateAddEvent info = new LogOperateAddEvent()
            {
                UserAgent = ua,
                Browser = client.UA.ToString(),
                Os = client.OS.ToString(),
                IP = IPUtils.GetIP(context.HttpContext.Request),
                City = "广东",
                UserName = currentUser.UserName,
                ApiName = ApiName,
                ApiUrl = context.ActionDescriptor.AttributeRouteInfo?.Template!,
                ApiMethod = context.HttpContext.Request.Method.ToLower(),
                ElapsedMilliseconds = sw.ElapsedMilliseconds,
                IsSuccess = isSuccess,
                Request = request,
                Response= response,
                //Response = JsonConvert.SerializeObject(actionResult?.Value)
            };
            await capPublisher.PublishAsync(nameof(LogOperateAddEvent), info);
        }
    }
}
